import React, {memo, PureComponent} from 'react';
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';
import 'prismjs/components/prism-sql';
import {format } from 'sql-formatter';
import styles from './index.less';
import {message} from 'antd';
 class Sql extends PureComponent {
   isUnmounted=false; //销毁异步循环
  constructor(props) {
    super(props);
    this.state = {
        expanded: false,
        mySql:"",
        twiceClick:true,
        endStatus:false,

    };
  }
  toggleExpand = async (expanded) => {
      await   this.props.changeScrollStatus("scroll")
      this.setState({
        expanded: expanded,
        endStatus:this.state.twiceClick? false:true,
      }, async ()=>{
        if(this.state.twiceClick){
         await this.props.getStatus(this.props.name,"detail")
        }
     await  this.disposeSqlSlice(7)
      });
  };
  //初始化
 async componentDidMount() {
    Prism.highlightAll();
    await this.disposeSqlSlice()
  }
   componentWillUnmount() {
    this.isUnmounted = true
   }

   componentDidUpdate(prevProps, prevState, snapshot) {
     if(!this.props.scrollStatus){
       this.props.handleScroll()
     }
     if(prevProps.sql!==this.props.sql) {
        this.disposeSqlSlice()
     }
   }

   sqlFormat = (text ) => {
    if (!text) return '';
    try {
        let a=format(text, {
        expressionWidth: 500,
        paramTypes: {
          custom: [{ regex: String.raw`#\{.+?\}` }],
        },
      });
      return a
    } catch (error) {
      return text
    }
  }
   //间断时间
    wordDelay = ms => {
     return new Promise(resolve => setTimeout(resolve, ms));
   };
   //  文字展示
    wordPrint = (index, sqlStr,mark) => {
      const {getStatus,name}= this.props
     if(mark){
       this.setState({
         mySql:sqlStr
       }, ()=>{
         Prism.highlightAll();
        getStatus(name)
         this.setState({
           endStatus:true
         })
       })
     }else {
       this.setState({
         mySql:sqlStr.slice(0,index)
       },()=>{
         Prism.highlightAll();
       })
     }

   };
    wordShow = async (wordConfig,time,startIndex) => {
     let index = startIndex||0;
     const sql = this.sqlFormat(wordConfig)
     const reg = /\n/g
     let matchBr = []
     let match;
     while ((match = reg.exec(sql) )!== null) {
       matchBr.push(match.index+2)
     }
     while (index <= matchBr.length&&!this.props.stop&&!this.isUnmounted) {
          if(index===matchBr.length){
            this.wordPrint(matchBr[index], sql,"end");
          }else {
            this.wordPrint(matchBr[index], sql);
          }
          await this.wordDelay(time);
          index++
     }
   };
  //sql 逐字打印效果
   disposeSqlSlice=async (index)=>{
     const { sql } = this.props;
     const { expanded,twiceClick } = this.state;
     let formattedSql = this.sqlFormat(sql);
     const displayedSql = expanded? formattedSql : `${formattedSql.split('\n').slice(0, 8).join('\n')}`;
     if(twiceClick){
       await  this.wordShow(displayedSql,100,index)
       if(expanded){
         this.setState({
           twiceClick:false,
         })
       }
     }else {
       this.wordPrint(index, displayedSql,"end")
     }
   }
  render() {
    const { sql } = this.props;
    const { mySql,expanded,endStatus } = this.state;
    let formattedSql = this.sqlFormat(sql);
    const lineCount = (formattedSql.match(/\n/g) || []).length;
    const shouldShowToggle = lineCount > 7;
    const handleCopy = async () => {
      // 获取要复制的文本
      let text = sql;
      // 创建一个临时的textarea元素
      let tempTextArea = document.createElement("textarea");
      tempTextArea.value = text;
      document.body.appendChild(tempTextArea);

      // 选中临时textarea中的文本并执行复制操作
      tempTextArea.select();
      document.execCommand("copy");
      message.success('复制成功 !');
      // 移除临时textarea元素
      document.body.removeChild(tempTextArea);
    };
    return (
      <div className={styles.mySql}>
        <pre style={{background: "#FAFAFA"}}>
          <div className={styles.textBtn} onClick={handleCopy}>复制</div>
          <code className="language-sql">
            {mySql}
          </code>
          {shouldShowToggle && (
            <div className={styles.textBtn} onClick={() => this.toggleExpand(!expanded)}>
              {endStatus?(expanded  ? '收起' : '详情'):""}
            </div>
          )}
        </pre>
      </div>
    )
      ;
  }
 }

export default Sql
